<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.currentId ? '新增课程' : isReadOnly ? '查看课程' : '修改课程'"
    :close-on-click-modal="false"
    width="900px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      @onclick="onSubmit()"
    >
      <el-form-item
        label="课程标题"
        prop="title"
      >
        <el-input
          v-model="dataForm.title"
          placeholder="请输入课程标题"
          :disabled="isReadOnly"
        />
      </el-form-item>
      <el-form-item
        label="讲课老师"
        prop="teacherName"
      >
        <el-autocomplete
          v-model="dataForm.teacherName"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入内容"
          :disabled="isReadOnly"
          @select="handleSelect"
        />
      </el-form-item>
      <el-form-item
        label="课程分类"
        prop="categoryId"
      >
        <el-select
          v-model="dataForm.categoryId"
          placeholder="请选择课程分类"
          :disabled="isReadOnly"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="课程封面"
        prop="coverImage"
      >
        <pic-upload
          v-model="dataForm.coverImage"
          :disabled="isReadOnly"
          @update:model-value="checkImage"
        />
      </el-form-item>
      <el-form-item
        label="课程描述"
        prop="description"
      >
        <el-input
          v-model="dataForm.description"
          type="textarea"
          :autosize="{minRows: 3, maxRows: 5}"
          placeholder="请输入课程描述"
          :disabled="isReadOnly"
        />
      </el-form-item>
      <el-form-item
        label="原价"
        prop="originalPrice"
      >
        <el-input-number
          v-model="dataForm.originalPrice"
          :precision="2"
          :min="0"
          :disabled="isReadOnly"
        />
      </el-form-item>
      <el-form-item
        label="现价"
        prop="currentPrice"
      >
        <el-input-number
          v-model="dataForm.currentPrice"
          :precision="2"
          :min="0"
          :disabled="isReadOnly"
        />
      </el-form-item>
      <el-form-item
        label="是否免费"
        prop="isFree"
      >
        <el-radio-group v-model="dataForm.isFree" :disabled="isReadOnly">
          <el-radio :label="0">
            否
          </el-radio>
          <el-radio :label="1">
            是
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="课程难度"
        prop="difficulty"
      >
        <el-select
          v-model="dataForm.difficulty"
          placeholder="请选择难度"
          :disabled="isReadOnly"
        >
          <el-option
            label="初级"
            :value="1"
          />
          <el-option
            label="中级"
            :value="2"
          />
          <el-option
            label="高级"
            :value="3"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="有效期(天)"
        prop="validity"
      >
        <el-input-number
          v-model="dataForm.validity"
          controls-position="right"
          :min="0"
          :disabled="isReadOnly"
        />
      </el-form-item>
      <el-form-item
        label="适合人群"
        prop="suitablePeople"
      >
        <el-input
          v-model="dataForm.suitablePeople"
          placeholder="请输入适合人群"
          :disabled="isReadOnly"
        />
      </el-form-item>
      <el-form-item
        label="课程标签"
        prop="coursesTabs"
      >
        <el-input
          v-model="dataForm.coursesTabs"
          placeholder="请输入课程标签(英文逗号隔开)"
          :disabled="isReadOnly"
        />
      </el-form-item>
      <el-form-item
        label="是否热门"
        prop="isHot"
      >
        <el-radio-group v-model="dataForm.isHot" :disabled="isReadOnly">
          <el-radio :label="0">
            否
          </el-radio>
          <el-radio :label="1">
            是
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 课程特色 -->
      <el-divider>课程特色</el-divider>
      <el-table
        :data="dataForm.characteristics"
        border
        style="width: 100%; margin-bottom: 20px;"
      >
        <el-table-column
          header-align="center"
          align="center"
          label="特色标题"
        >
          <template #default="scope">
            <el-form-item
              :prop="`characteristics.${scope.$index}.title`"
              label-width="0px"
            >
              <el-input
                v-model="scope.row.title"
                placeholder="特色标题"
                :disabled="isReadOnly"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="特色描述"
        >
          <template #default="scope">
            <el-form-item
              label-width="0"
              :prop="`characteristics.${scope.$index}.description`"
            >
              <el-input
                v-model="scope.row.description"
                type="textarea"
                :autosize="{minRows: 2, maxRows: 3}"
                placeholder="特色描述"
                :disabled="isReadOnly"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          width="100"
          label="操作"
        >
          <template #default="scope">
            <el-button
              v-if="!isReadOnly"
              type="danger"
              size="small"
              @click="removeCharacteristic(scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        v-if="!isReadOnly"
        type="primary"
        icon="el-icon-plus"
        style="margin-bottom: 20px;"
        @click="addCharacteristic()"
      >
        添加课程特色
      </el-button>

      <!-- 课程章节及课时 -->
      <el-divider>课程章节</el-divider>
      <div
        v-for="(chapter, chapterIndex) in dataForm.chapters"
        :key="chapterIndex"
        class="chapter-container"
      >
        <!-- 章节信息 -->
        <div style="margin-bottom: 15px;">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="章节标题"
                label-width="80px"
              >
                <el-input
                  v-model="chapter.title"
                  placeholder="请输入章节标题"
                  :disabled="isReadOnly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="排序"
                label-width="80px"
              >
                <el-input-number
                  v-model="chapter.sortOrder"
                  :min="1"
                  controls-position="right"
                  :disabled="isReadOnly"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="章节描述" label-width="80px">
            <el-input
              v-model="chapter.description"
              type="textarea"
              :autosize="{minRows: 2, maxRows: 3}"
              placeholder="请输入章节描述"
              :disabled="isReadOnly"
            />
          </el-form-item>
        </div>

        <!-- 课时列表 -->
        <div style="margin-bottom: 15px;">
          <div class="lesson-list-title">
            课时列表
          </div>
          <el-table
            :data="chapter.lessons || []"
            border
            style="width: 100%; margin-bottom: 10px;"
          >
            <el-table-column
              header-align="center"
              align="center"
              label="课时标题"
              width="200"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.title"
                  placeholder="课时标题"
                  size="small"
                  :disabled="isReadOnly"
                />
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="课时描述"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.description"
                  type="textarea"
                  :autosize="{minRows: 1, maxRows: 2}"
                  placeholder="课时描述"
                  size="small"
                  :disabled="isReadOnly"
                />
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="排序"
              width="80"
            >
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.sortOrder"
                  :min="1"
                  size="small"
                  controls-position="right"
                  :disabled="isReadOnly"
                />
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="免费"
              width="80"
            >
              <template #default="scope">
                <el-switch
                  v-model="scope.row.isFree"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="isReadOnly"
                />
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="课时视频"
              width="150"
            >
              <template #default="scope">
                <video-upload
                  v-model="scope.row.contentUrl"
                  :disabled="isReadOnly"
                  :fileName="scope.row.fileName"
                  @upload-success="(data) => handleVideoUploadSuccess(scope.$index, scope.row, data)"
                />
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="操作"
              width="100"
            >
              <template #default="scope">
                <el-button
                  v-if="!isReadOnly"
                  type="danger"
                  size="small"
                  @click="removeLesson(chapterIndex, scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            v-if="!isReadOnly"
            type="primary"
            size="small"
            @click="addLesson(chapterIndex)"
          >
            添加课时
          </el-button>
        </div>

        <!-- 删除章节按钮 -->
        <el-button
          v-if="!isReadOnly"
          type="danger"
          @click="removeChapter(chapterIndex)"
        >
          删除章节
        </el-button>
      </div>

      <!-- 添加章节按钮 -->
      <el-button
        v-if="!isReadOnly"
        type="primary"
        icon="el-icon-plus"
        style="margin-bottom: 20px;"
        @click="addChapter()"
      >
        添加章节
      </el-button>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">
          取消
        </el-button>
        <el-button
          v-if="!isReadOnly"
          type="primary"
          @click="onSubmit()"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Debounce } from '@/utils/debounce'

const emit = defineEmits(['refreshDataList'])
const props = defineProps({
  categoryList: {
    type: Array,
    default: () => []
  }
})

const visible = ref(false)
const isReadOnly = ref(false)
const dataForm = reactive({
  id: 0,
  currentId: 0,
  title: '',
  teacherName: '',
  teacherId: 0,
  categoryId: '',
  coverImage: '',
  description: '',
  originalPrice: 0,
  currentPrice: 0,
  isFree: 0,
  difficulty: 1,
  validity: 365,
  suitablePeople: '',
  coursesTabs: '',
  isHot: 0,
  characteristics: [],
  chapters: []
})

const dataRule = reactive({
  title: [
    { required: true, message: '课程标题不能为空', trigger: 'blur' },
    { min: 2, max: 100, message: '课程标题长度应在2-100个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '课程分类不能为空', trigger: 'change' }
  ],
  teacherName: [
    { required: true, message: '课程老师还未选择', trigger: 'change' }
  ],
  description: [
    { min: 10, max: 500, message: '课程描述长度应在10-500个字符之间', trigger: 'blur' }
  ]
})

const isSubmit = ref(false)
const dataFormRef = ref(null)

const init = (id, readOnly = false) => {
  visible.value = true
  isReadOnly.value = readOnly
  dataForm.currentId = id || 0
  dataForm.id = id || 0
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
  if (dataForm.id) {
    // 修改 - 获取课程详情
    http({
      url: http.adornUrl(`/admin/course/info/${dataForm.id}`),
      method: 'get',
      params: http.adornParams()
    })
      .then(({ data }) => {
        Object.assign(dataForm, {
          id: data.id,
          title: data.title,
          teacherName: data.teacherName,
          teacherId: data.teacherId,
          categoryId: data.categoryId,
          coverImage: data.coverImage,
          description: data.description,
          originalPrice: data.originalPrice,
          currentPrice: data.currentPrice,
          isFree: data.isFree,
          difficulty: data.difficulty,
          validity: data.validity,
          suitablePeople: data.suitablePeople,
          coursesTabs: data.coursesTabs,
          isHot: data.isHot,
          characteristics: data.characteristics || [],
          chapters: data.chapters || []
        })
        visible.value = true
      })
      .catch(() => {
        ElMessage.error('获取课程信息失败')
      })
  } else {
    // 新增 - 初始化空数据
    dataForm.characteristics = []
    dataForm.chapters = []
  }
  getTeacherList()
}

defineExpose({ init })

/**
 * 重新校验表单pic字段
 */
const checkImage = () => {
  dataFormRef.value?.validateField('coverImage')
}

/**
 * 添加课程特色
 */
const addCharacteristic = () => {
  dataForm.characteristics.push({
    title: '',
    description: ''
  })
}

/**
 * 删除课程特色
 */
const removeCharacteristic = (index) => {
  dataForm.characteristics.splice(index, 1)
  ElMessage.success('特色已删除')
}

/**
 * 添加章节
 */
const addChapter = () => {
  dataForm.chapters.push({
    title: '',
    description: '',
    sortOrder: dataForm.chapters.length + 1,
    lessons: []
  })
  ElMessage.success('章节已添加')
}

/**
 * 删除章节
 */
const removeChapter = (index) => {
  dataForm.chapters.splice(index, 1)
  ElMessage.success('章节已删除')
}

/**
 * 添加课时
 */
const addLesson = (chapterIndex) => {
  const chapter = dataForm.chapters[chapterIndex]
  if (!chapter.lessons) {
    chapter.lessons = []
  }
  chapter.lessons.push({
    title: '',
    description: '',
    sortOrder: chapter.lessons.length + 1,
    isFree: 0,
    contentType: 'video',
    contentUrl: ''
  })
  ElMessage.success('课时已添加')
}

/**
 * 删除课时
 */
const removeLesson = (chapterIndex, lessonIndex) => {
  dataForm.chapters[chapterIndex].lessons.splice(lessonIndex, 1)
  ElMessage.success('课时已删除')
}

/**
 * 视频上传成功，自动填充时长
 */
const handleVideoUploadSuccess = (_, lesson, data) => {
  if (data && data.duration) {
    lesson.duration = data.duration
    lesson.contentUrl = data?.filePath.url
    lesson.fileName = data?.filePath.name
    ElMessage.success(`视频时长已自动填充: ${data.duration}秒`)
  }
}

/**
 * input的搜索
 */
const inputData = reactive({
  restaurants: [],
  state: '',
  timeoutFun: null
})

const querySearchAsync = (queryString, cb) => {
  const restaurants = inputData.restaurants
  const results = queryString ? restaurants.filter(createStateFilter(queryString)) : restaurants
  clearTimeout(inputData.timeoutFun)
  inputData.timeoutFun = setTimeout(() => {
    cb(results)
  }, 3000 * Math.random())
}

const createStateFilter = (queryString) => {
  return (state) => {
    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
  }
}

const getTeacherList = () => {
  http({
    url: http.adornUrl('/admin/user/list'),
    method: 'get',
    params: http.adornParams({roleId: 1})
  })
    .then(({ data }) => {
      const list = []
      for (let i = 0; i < data.length; i++) {
        const obj = {
          value: data[i].realName,
          teacherId: data[i].userId
        }
        list.push(obj)
      }
      inputData.restaurants = list
    })
}

const handleSelect = (item) => {
  dataForm.teacherName = item.value
  dataForm.teacherId = item.teacherId
}

/**
 * 表单提交
 */
const onSubmit = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error('请填写完整的表单信息')
      return
    }

    if (isSubmit.value) {
      return
    }

    isSubmit.value = true
    const isUpdate = !!dataForm.id

    http({
      url: http.adornUrl(`/admin/course/${isUpdate ? 'update' : 'add'}`),
      method: 'post',
      data: http.adornData({
        id: dataForm.id || undefined,
        title: dataForm.title,
        teacherId: dataForm.teacherId,
        categoryId: dataForm.categoryId,
        coverImage: dataForm.coverImage,
        description: dataForm.description,
        originalPrice: dataForm.originalPrice,
        currentPrice: dataForm.currentPrice,
        isFree: dataForm.isFree,
        difficulty: dataForm.difficulty,
        validity: dataForm.validity,
        suitablePeople: dataForm.suitablePeople,
        coursesTabs: dataForm.coursesTabs,
        isHot: dataForm.isHot,
        characteristics: dataForm.characteristics,
        chapters: dataForm.chapters
      })
    })
      .then(() => {
        ElMessage.success(`课程${isUpdate ? '修改' : '新增'}成功`)
        isSubmit.value = false
        visible.value = false
        emit('refreshDataList')
      })
      .catch((error) => {
        isSubmit.value = false
        ElMessage.error(error?.message || '操作失败，请重试')
      })
  })
})
</script>

<style scoped>
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-divider) {
  margin: 20px 0;
  font-weight: 600;
  color: #333;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table__header th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

.chapter-container {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.chapter-container:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.lesson-list-title {
  margin-bottom: 10px;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
